<template>
  <el-dialog 
    v-model="visible" 
    :title="`运输车工作详情 - ${vehicleInfo.title || vehicleInfo.vehicleNumber}`" 
    :destroy-on-close="true" 
    width="90%" 
    draggable 
    append-to-body
    :close-on-click-modal="false"
  >
    <div class="work-detail-container">
      <!-- 车辆基本信息 -->
      <!-- <el-card class="vehicle-info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>车辆基本信息</span>
          </div>
        </template>
        <el-descriptions :column="4" border>
          <el-descriptions-item label="车辆ID">{{ vehicleInfo.vehicleId }}</el-descriptions-item>
          <el-descriptions-item label="车辆编号">{{ vehicleInfo.vehicleNumber }}</el-descriptions-item>
          <el-descriptions-item label="车辆名称">{{ vehicleInfo.title || '未填写' }}</el-descriptions-item>
          <el-descriptions-item label="部门">{{ vehicleInfo.deptName || '未填写' }}</el-descriptions-item>
        </el-descriptions>
      </el-card> -->

      <!-- 工作记录表格 -->
      <el-card class="work-table-card" shadow="hover" style="margin-top: 20px;">
        <template #header>
          <div class="card-header">
            <span>工作记录列表</span>
          </div>
        </template>
        <el-table 
          :data="groupedWorkData" 
          style="width: 100%" 
          row-key="date"
          v-loading="loading"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column type="expand">
            <template #default="scope">
              <div class="work-detail-content">
                <el-table 
                  :data="scope.row.records" 
                  stripe 
                  style="width: 100%"
                  :default-sort="{ prop: 'createTime', order: 'descending' }"
                >
                  <el-table-column prop="id" label="记录ID" width="80" />
                  <el-table-column prop="originalFilename" label="原始文件名" width="150" show-overflow-tooltip />
                  <el-table-column prop="createTime" label="创建时间" sortable />
                  <el-table-column prop="carNumber" label="车牌号" width="120" />
                  <el-table-column prop="fileTag" label="设备编号" width="120" />
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="日期" sortable />
          <el-table-column prop="records" label="工作记录数量" width="120" sortable>
            <template #default="scope">
              <el-tag type="primary">{{ scope.row.records.length }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="pagination.total > 0"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          :current-page="pagination.current"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.size"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 20px; justify-content: flex-end;"
        />
      </el-card>
    </div>

    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import type { TransportVehicleInfo } from '@/api/types/datainfo/dataStatistics';
import { getVehicleWorkDetails } from '@/api/modules/datainfo/dataStatistics';

defineOptions({
  name: 'WorkDetail'
});

// Define types for the work data based on the actual API response
interface WorkRecord {
  id: number;
  monitorId: number;
  monitorDescription: string;
  originalPath: string;
  originalFilename: string;
  newFilename: string;
  storagePath: string;
  fileSize: number;
  fileType: string;
  fileUrl: string;
  processStatus: string;
  processStatusDisplay: string;
  errorMessage: string;
  processTime: string;
  fileMd5: string;
  fileTag: string;
  carNumber: string;
  carNumberRes: string;
  createTime: string;
  createDate: string;
  deptName: string;
  driverId: number;
  driverName: string;
}

interface GroupedWorkData {
  date: string;
  records: WorkRecord[];
}

// Response data structure based on the actual API response
interface VehicleWorkDetailsResponse {
  current: number;
  limit: number;
  totalPage: number;
  total: number;
  rows: GroupedWorkData[];
}

const visible = ref(false);
const loading = ref(false);
const vehicleInfo = ref<TransportVehicleInfo>({} as TransportVehicleInfo);
const currentVehicleId = ref<number>(0);
const groupedWorkData = ref<GroupedWorkData[]>([]);

// Pagination
const pagination = reactive({
  total: 0,
  size: 10,
  pages: 1,
  current: 1
});

// Handle page change
const handlePageChange = (page: number) => {
  pagination.current = page;
  loadVehicleWorkDetails();
};

// Handle size change
const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1; // Reset to first page
  loadVehicleWorkDetails();
};

// Load vehicle work details
const loadVehicleWorkDetails = async () => {
  if (!currentVehicleId.value) return;
  
  loading.value = true;
  try {
    const response = await getVehicleWorkDetails(currentVehicleId.value, {
      page: pagination.current,
      limit: pagination.size
    });
    
    if (response.code === "0000") {
      groupedWorkData.value = response.data.rows || [];
      pagination.total = response.data.total || 0;
      pagination.pages = response.data.totalPage || 1;
      pagination.current = response.data.current || 1;
    } else {
      ElMessage.error(response.message || '获取工作详情失败');
    }
  } catch (error) {
    console.error('Failed to load vehicle work details:', error);
    ElMessage.error('获取工作详情失败');
  } finally {
    loading.value = false;
  }
};

// 接收父组件传过来的参数
const acceptParams = (vehicle: TransportVehicleInfo, vehicleId: number) => {
  vehicleInfo.value = vehicle;
  currentVehicleId.value = vehicleId;
  
  visible.value = true;
  
  // 延迟一点再加载数据，确保组件已经正确初始化
  setTimeout(() => {
    loadVehicleWorkDetails();
  }, 100);
};

defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss">
.work-detail-container {
  .vehicle-info-card {
    margin-bottom: 20px;
  }
  
  .work-table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .work-detail-content {
    padding: 20px;
    background-color: #f8f9fa;
  }
}
</style>